package pub.tbc.rubbish.client.util;

import pub.tbc.rubbish.client.Constant;
import pub.tbc.toolkit.Objs;
import pub.tbc.toolkit.PropsUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author tbc on 2016/12/7 10:16:15.
 */
public class RedisHelper {
    private static JedisPool pool = null;

    private static String getRedisHost() {
        return PropsUtil.getString(
                PropsUtil.load(Constant.DEFAULT_CONFIG_FILE),
                Constant.REDIS_PORT_KEY,
                "192.168.1.11"
        );
    }

    private static int getRedisPort() {
        return PropsUtil.getInt(
                PropsUtil.load(Constant.DEFAULT_CONFIG_FILE),
                Constant.REDIS_PORT_KEY,
                6379
        );
    }

    private static void initPool() {
        if (Objs.isEmpty(pool)) {
            synchronized (RedisHelper.class) {
                pool = new JedisPool(new JedisPoolConfig(), getRedisHost(), getRedisPort());
            }
        }
    }

    public static Jedis getClientFromPool() {
        if (Objs.isEmpty(pool)) {
            synchronized (RedisHelper.class) {
                if (Objs.isEmpty(pool)) pool = new JedisPool(new JedisPoolConfig(), getRedisHost(), getRedisPort());
            }
        }
        return pool.getResource();
    }

    public static Jedis createClient() {
        return new Jedis(getRedisHost(), getRedisPort());
    }
}
